﻿#include "DownloadFileResponse1Private.h"
#include "qftp.h"
#include "DownloadFileResponse1.h"

BEGIN_NAMESPACE_ZFTPNS

DownloadFileResponse1Private::DownloadFileResponse1Private(QObject *parent) :
    ZFtpResponsePrivate(parent),
    q_ptr(NULL)
{

}

void DownloadFileResponse1Private::listenTo(QSharedPointer<QFtp> ftp, QSharedPointer<ZFtpConfig> ftp_config)
{
    // 保证继承的信号工作
    ZFtpResponsePrivate::listenTo(ftp, ftp_config);

    if (!ftp) return;

    m_current_ftp = ftp;

    ftp->disconnect(this, SLOT(slotCommandFinished(int,bool)));
    ftp->disconnect(this, SLOT(slotDownloadFileProgress(qint64,qint64)));
    ftp->disconnect(this, SLOT(slotFtpStateChanged(int)));

    connect(ftp.data(), SIGNAL(commandFinished(int,bool)), SLOT(slotCommandFinished(int,bool)));
    connect(ftp.data(), SIGNAL(dataTransferProgress(qint64,qint64)), SLOT(slotDownloadFileProgress(qint64,qint64)));
    connect(ftp.data(), SIGNAL(stateChanged(int)), SLOT(slotFtpStateChanged(int)));
}

void DownloadFileResponse1Private::setPublicResponseObject(QPointer<ZFtpResponse> response)
{
    ZFtpResponsePrivate::setPublicResponseObject(response);
    q_ptr = qobject_cast<DownloadFileResponse1 *>(response.data());
    Q_ASSERT(q_ptr);
}

QPointer<ZFtpResponse> DownloadFileResponse1Private::publicObject()
{
    return QPointer<ZFtpResponse>(q_ptr);
}

void DownloadFileResponse1Private::slotDownloadFileProgress(qint64 done, qint64 total)
{
    Q_ASSERT(m_current_ftp);
    if (m_current_ftp->currentId() != this->ftpTaskID())
        return;

    emit q_ptr->sigDownloadProgress(done, total);
}

void DownloadFileResponse1Private::slotCommandFinished(int id, bool error)
{
    if (id != ftpTaskID()) return;
    invalidFtpTaskID();

    Q_ASSERT(q_ptr);
#if 0
    emit q_ptr->sigResult(!error);
#else
    // 异步非阻塞消息
    QMetaObject::invokeMethod(q_ptr, "sigResult", Qt::QueuedConnection, Q_ARG(bool, !error));
#endif
}

void DownloadFileResponse1Private::slotFtpStateChanged(int state)
{

}

END_NAMESPACE
